package ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zzhoujay.richtext.ImageHolder;
import com.zzhoujay.richtext.RichText;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Dailog.CommomDialog;
import adapter.NoteAdapter;
import base.BaseBean;
import base.activity.BaseNetActivity;
import bean.NoteCategoryBean;
import bean.NoteDetailBean;
import student.andlei.com.student.R;
import utils.DensityUtil;
import utils.GsonUtils;
import utils.StringUtils;
import view.ClearEditText;

/**
 * 我的笔记
 */
public class MyNoteActivity extends BaseNetActivity {
    private ImageView img_add,
            img_fenlei,
            img_amend,
            img_delete;
          //  img_content;
    private TextView img_content;
    private TextView tv_list_title,
            tv_title;
//            tv_content,
//            tv_content2;
    private RecyclerView recyclerView;
    private ClearEditText clearEditText;
    private int note_id;//笔记id
    private int category_id;//分类id
    private String category_name;//分类名称
    private List<NoteCategoryBean> lists = new ArrayList();
    private NoteAdapter noteadapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseBack(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("category_id",category_id);
                setResult(3);
                finish();
            }
        });
        setTitle("我的笔记");
    }

    @Override
    public void success(String action, BaseBean baseBean) {
        if (baseBean.code == 200) {
            if (action.equals("note/noteDetail")) {
                NoteDetailBean detailBean = (NoteDetailBean) GsonUtils.JSONToObject(GsonUtils.beanToJSONString(baseBean.data), NoteDetailBean.class);
                img_content.setText("");
                tv_title.setText(detailBean.title);
                //在第一次调用RichText之前先调用RichText.initCacheDir()方法设置缓存目录，不设置会报错
                RichText.initCacheDir(this);
                RichText.from(detailBean.content).bind(this)
                        .showBorder(false)
                        .size(ImageHolder.MATCH_PARENT, ImageHolder.WRAP_CONTENT)
                        .into(img_content);
                //img_content.setCommenListText(detailBean.content);
                //setMmContentList(img_content.getmContentList(detailBean.content));
            } else if (action.equals("note/noteList")) {
                lists = GsonUtils.getInstance(context).parseNoHeaderJArray(baseBean, NoteCategoryBean.class);
                noteadapter.setNewData(lists);
                if(lists.size()>0){
                    note_id = lists.get(0).note_id;
                    Map<String, String> map = new HashMap<>();
                    map.put("note_id", "" + note_id);
                    post("note/noteDetail", map, BaseBean.class, false);
                }else {
                   finish();
                }
            } else if(action.equals("note/delNote")){
                Map<String, String> smap = new HashMap<>();
                smap.put("category_id", category_id + "");
                smap.put("title", clearEditText.getText().toString());
                post("note/noteList", smap, NoteCategoryBean.class, false);
            }
        } else {
            toast(baseBean.msg);
        }
    }

    @Override
    public void error(String action, Throwable e) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_mynote;
    }

    @Override
    protected void findViews() {
        img_add = getView(R.id.img_add);
        img_amend = getView(R.id.img_amend);
        img_fenlei = getView(R.id.img_fenlei);
        img_delete = getView(R.id.img_delete);
        img_content = getView(R.id.img_content);
        tv_list_title = getView(R.id.tv_note_title);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) tv_list_title.getLayoutParams();
        layoutParams.width = DensityUtil.dp2pxInt(90);
        tv_list_title.setLayoutParams(layoutParams);
      //  tv_list_title.setWidth(DensityUtil.dp2pxInt(60));
        tv_title = getView(R.id.tv_content_title);
        img_content = getView(R.id.ed_content);
//        tv_content = getView(R.id.tv_content);
//        tv_content2 = getView(R.id.tv_content2);
        recyclerView = getView(R.id.rcly_);
        clearEditText = getView(R.id.edittext_search);
    }

    @Override
    protected void formatViews() {
        img_add.setOnClickListener(this);
        img_fenlei.setOnClickListener(this);
        img_delete.setOnClickListener(this);
        img_amend.setOnClickListener(this);
        clearEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null) {
                    loadData();
                }
                return false;

            }
        });
        clearEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(StringUtils.isNull(s.toString())){
                    loadData();
                }
            }
        });

    }

    @Override
    protected void formatData() {
        //创建布局管理
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        //创建适配器
        noteadapter = new NoteAdapter(this, R.layout.item_note, lists);
        //给RecyclerView设置适配器
        recyclerView.setAdapter(noteadapter);
        noteadapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                note_id = lists.get(position).note_id;
                Map<String, String> map = new HashMap<>();
                map.put("note_id", "" + note_id);
                post("note/noteDetail", map, BaseBean.class, false);
            }
        });
        tv_list_title.setText(category_name);
        loadData();
    }

    private void loadData() {
        Map<String, String> map = new HashMap<>();
        map.put("note_id", "" + note_id);
        post("note/noteDetail", map, BaseBean.class, false);
        Map<String, String> smap = new HashMap<>();
        smap.put("category_id", category_id + "");
        smap.put("title", clearEditText.getText().toString());
        post("note/noteList", smap, NoteCategoryBean.class, false);
    }

    @Override
    protected void getBundle(Bundle bundle) {
        category_name = bundle.getString("category_name");
        category_id = bundle.getInt("category_id");
        note_id = bundle.getInt("note_id");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_add:
                Bundle msbundle = new Bundle();
                msbundle.putString("typename",""+tv_list_title.getText().toString().trim());
                jumpTo(AddNewNoteActivity.class,msbundle);
                break;
            case R.id.img_fenlei:
                Bundle bundle = new Bundle();
                bundle.putInt("note_id", note_id);
                bundle.putInt("category_id",category_id);
                jumpTo(AmendNoteActivity.class,0,bundle);
                break;
            case R.id.img_amend:
                Bundle mbundle = new Bundle();
                mbundle.putInt("note_id", note_id);
                mbundle.putString("typename",""+tv_list_title.getText().toString().trim());
                jumpTo(AddNewNoteActivity.class,mbundle);
                break;
            case R.id.img_delete:
                new CommomDialog(MyNoteActivity.this, R.style.dialog, "是否删除该笔记", new CommomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            Map<String, String> map = new HashMap<>();
                            map.put("note_id", "" + note_id);
                            post("note/delNote", map, BaseBean.class, false);
                            dialog.dismiss();
                        }
                    }
                }).setTitle("提示").settPositiveButtonColor(R.color.homepage_titlefont).show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 2 && data!=null){
            category_id = data.getIntExtra("category_id",0);
            note_id = data.getIntExtra("note_id",0);
            tv_list_title.setText(data.getStringExtra("category_name"));
            loadData();
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        //结束时清空内容
        RichText.clear(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }
}
